define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Productmanager_brand_agent_edit, GoAddress, GoDialog, Auth, GoCatTypeAuth, GoPage,$ionicModal,$ionicScrollDelegate,$stateParams) {

		//数据模型
		$scope.input = new Object();
	  	$scope.input.id = $stateParams.id;
		$scope.input.search_words_brand = "";
		$scope.cats = new Array(); //显示的类目，不提交
		$scope.regions = new Array(); //显示的地区，不提交
		$scope.input.brand = null;//品牌
		$scope.input.cat_type = new Array(); //提交，格式AAA/BBB/CCC:CCC的id（最后一级的id）
		$scope.input.region = new Array(); //提交，格式AAA/BBB/CCC:CCC的id（最后一级的id）
		
		$scope.initialize = function(){//后面要初始化这3个参数，所以把他们放在函数里
            $scope.input.cat1 = {id:0,name:"请选择大分类"};
            $scope.input.cat2 = {id:0,name:"请选择中分类"};
            $scope.input.cat3 = {id:0,name:"请选择小分类"};
			$scope.input.province = {id:0,name:"请选择省份"}; //省市区三级联动
			$scope.input.city = {id:0,name:"请选择城市"}; //省市区三级联动
			$scope.input.district = {id:0,name:"请选择区/县"}; //省市区三级联动
        }
        $scope.initialize();
        
        
        //初始化页面
		$scope.init_data = function(){
			if(!$scope.input.id) return;
			Productmanager_brand_agent_edit.detail($scope.input.id,function(data){
				var detail = data.result;
				$scope.scope = detail;//status 1：审核中  2：使用中   3：审核失败
				console.log(detail)
				$scope.input.brand = {'id':detail.brand_id,'name':detail.name,'brand_desc':detail.brand_desc,'store_id':detail.parent_store_id};
				for (var i=0;i<detail.goods_cat.length;i++) {
					$scope.cats.push(detail.goods_cat[i].cat_name);
        			$scope.input.cat_type.push(detail.goods_cat[i].cat_name+":"+detail.goods_cat[i].cat_id);//格式不能错
				}
				for (var i=0;i<detail.store_region.length;i++) {
					$scope.regions.push(detail.store_region[i].region_name);
        			$scope.input.region.push(detail.store_region[i].region_name+":"+detail.store_region[i].region_id);//格式不能错
				}
			})
		}
		$scope.init_data();
        
        

		/***************省市区三级联动***************s*/
		$scope.listen_province = function(data, obj) {
			$scope.input.city = {id:0,name:"请选择城市"}; //省市区三级联动
			$scope.input.district = {id:0,name:"请选择区/县"}; //省市区三级联动
		};
		$scope.listen_city = function(data, obj) {
			$scope.input.district = {id:0,name:"请选择区/县"}; //省市区三级联动
		};
		$scope.doSelectProvince = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择省份",$scope.province_items,$scope.input.province,function(data){
				$scope.input.province = data;
			});
		}
		$scope.doSelectCity = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择城市",$scope.city_items,$scope.input.city,function(data){
				$scope.input.city = data;
			});
		}
		$scope.doSelectDistrict = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择区/县",$scope.district_items,$scope.input.district,function(data){
				$scope.input.district = data;
			});
		}
		//定义绑定
		var items = new Array();
		var obj1 = { name: 'input.province' };
		var obj2 = { name: 'input.city' };
		var obj3 = { name: 'input.district' };
		items.push(obj1);
		items.push(obj2);
		items.push(obj3);
		GoAddress.init_load($scope, items);
		$scope.doSelectCat1 = function(){
			//id是值 name是显示
			GoDialog.showSelect("大分类",$scope.cat1_items,$scope.input.cat1,function(data){
				$scope.input.cat1 = data;
			});
		}
		$scope.doSelectCat2 = function(){
			//id是值 name是显示
			GoDialog.showSelect("中分类",$scope.cat2_items,$scope.input.cat2,function(data){
				$scope.input.cat2 = data;
			});
		}
		$scope.doSelectCat3 = function(){
			//id是值 name是显示
			GoDialog.showSelect("小分类",$scope.cat3_items,$scope.input.cat3,function(data){
				$scope.input.cat3 = data;
			});
		}
		/*********************分类三级联动*****************/
		//监听品牌，获取一级分类
		$scope.$watch("input.brand",function(newVal){
			$scope.cat1_items = new Array();//一级
			$scope.cat2_items = new Array();//二级
			$scope.cat3_items = new Array();//三级
			if(newVal){
				var cat_id = "";
				$scope.brand_id = newVal.id;//一级监听、二级监听会用到
				$scope.store_id = newVal.store_id;//一级监听、二级监听会用到
				$scope.getCatList($scope.cat1_items,cat_id,$scope.brand_id,$scope.store_id);
			}
		})
		//监听一级分类，获取二级分类
		$scope.$watch("input.cat1",function(newVal){
			$scope.cat2_items = new Array();//二级
			$scope.cat3_items = new Array();//三级
			if(newVal){
				var cat_id = newVal.id;
				$scope.getCatList($scope.cat2_items,cat_id,$scope.brand_id,$scope.store_id);
			}
		})
		//监听二级分类，获取三级分类
		$scope.$watch("input.cat2",function(newVal){
			$scope.cat3_items = new Array();//三级
			if(newVal){
				var cat_id = newVal.id;
				$scope.getCatList($scope.cat3_items,cat_id,$scope.brand_id,$scope.store_id);
			}
		})
		
		//组装一级、二级、三级分类
		$scope.getCatList = function(name,cat_id,brand_id,store_id){
			Productmanager_brand_agent_edit.getCatList(cat_id,brand_id,store_id,function(data){
				for (var i=0;i<data.result.list.length;i++) {//将数组转换为对象
					var obj = new Object();
					obj.id = data.result.list[i][0];
					obj.name = data.result.list[i][1];
					name.push(obj)
				}
			})
		}
		/*********************分类三级联动*****************/
		
		/**********************品类、地区处理********************/
		//控制下拉框的显示--分类
        $scope.showSelectCat = function(){
        	$scope.isShowSelectCat = !$scope.isShowSelectCat;
        }
        //控制下拉框的显示--区域
        $scope.showSelectRegion = function(){
        	$scope.isShowSelectRegion = !$scope.isShowSelectRegion;
        }
		//添加分类
		$scope.add_type = function() {
			$scope.cat_id = "";
			$scope.cat_name = "";
      		if($scope.input.cat3){
        		$scope.cat_name=$scope.input.cat1.name+"/"+$scope.input.cat2.name+"/"+$scope.input.cat3.name;
        		$scope.cat_id=$scope.cat_name+":"+$scope.input.cat3.id;
        	}else if($scope.input.cat2){
        		$scope.cat_name=$scope.input.cat1.name+"/"+$scope.input.cat2.name;
        		$scope.cat_id=$scope.cat_name+":"+$scope.input.cat2.id;
        	}else if($scope.input.cat1){
        		$scope.cat_name=$scope.input.cat1.name;
        		$scope.cat_id=$scope.cat_name+":"+$scope.input.cat1.id;
        	}
        	if($scope.cat_id&&$scope.cat_name){
        		if($scope.check($scope.cat_name,1)){//判断是否已经添加过
        			$scope.cats.push($scope.cat_name);
	        		$scope.input.cat_type.push($scope.cat_id);
	        		$scope.initialize();//初始化分类3个modal
	        		$scope.showSelectCat();//添加完，关闭弹窗
        		}else{
        			GoDialog.toast("已存在该品类！");
        		}
        	}else{
        		GoDialog.toast("请选择品类！");
        	}
		};
		
		//添加地区
		$scope.add_region = function() {
			$scope.region_id = "";
			$scope.region_name = "";
      		if($scope.input.district){
        		$scope.region_name=$scope.input.province.name+"/"+$scope.input.city.name+"/"+$scope.input.district.name;
        		$scope.region_id=$scope.region_name+":"+$scope.input.district.id;
        	}else if($scope.input.city){
        		$scope.region_name=$scope.input.province.name+"/"+$scope.input.city.name;
        		$scope.region_id=$scope.region_name+":"+$scope.input.city.id;
        	}else if($scope.input.province){
        		$scope.region_name=$scope.input.province.name;
        		$scope.region_id=$scope.region_name+":"+$scope.input.province.id;
        	}
        	if($scope.region_id&&$scope.region_name){
        		if($scope.check($scope.region_name,2)){
        			$scope.regions.push($scope.region_name);
        			$scope.input.region.push($scope.region_id);
        			$scope.initialize();//初始化分类3个modal
        			$scope.showSelectRegion();//添加完，关闭弹窗
        		}else{
        			GoDialog.toast("已存在该地区！");
        		}
        	}else{
        		GoDialog.toast("请选择地区！");
        	}
		};
		//判断分类/区域的存在性
		$scope.check = function(names, type) {
			if(type == 1) {
				for(var i = 0; i < $scope.cats.length; i++) {
					if($scope.cats[i] == names){return false;}
				}
			} else {
				for(var i = 0; i < $scope.regions.length; i++) {
					console.log($scope.regions[i]);
					if($scope.regions[i] == names){
						return false;
					}
				}
			}
			return true;
		}
		
		//删除分类
		$scope.delete_cat = function(val) {
			$scope.cats.splice(val, 1); //在val下标删除一个元素，后面的元素会自己填充这个下标
			$scope.input.cat_type.splice(val, 1);
		}
		//删除地区
		$scope.delete_region = function(val){
			$scope.regions.splice(val, 1); //在val下标删除一个元素，后面的元素会自己填充这个下标
			$scope.input.region.splice(val, 1);
		}
		/**********************品类、地区处理********************/
		
		//保存
		$scope.submit = function() {
			if(!$scope.input.brand) {
				GoDialog.toast("请选择品牌");
			} else if($scope.input.cat_type.length == 0) {
				GoDialog.toast("请选择分类！");
			} else if($scope.input.region.length == 0){
				GoDialog.toast("请选择地域！");
			} else {
				Productmanager_brand_agent_edit.edit($scope.input.id,$scope.input.brand.id, $scope.input.cat_type, $scope.input.region, function(data) {
					if(data.success) {
						GoDialog.toast("保存成功！");
						GoPage.go_states("productmanager_brand");
					} else {
						GoDialog.toast(data.msg);
					}
				})
			}
		}
		
		
		/***********品牌按字母排序************/
		//搜索品牌
		$scope.doSearchBrand = function(){
			GoCatTypeAuth.init_brandsOrderBy($scope,$scope.input.search_words_brand);
		}
		$scope.doSearchBrand();//初始化品牌
		//选择搜索出的结果
		$scope.getSearchBrands = function(index,secondIndex){
			$scope.closebrandOrderBy();
			$scope.input.brand = $scope.brandsOrderBy[index].brands[secondIndex];
			console.log($scope.brandsOrderBy[index].brands[secondIndex]);
			//重新选择品牌，以下2个必须清空之前添加好的品类
			$scope.cats = new Array(); //显示的类目，不提交
			$scope.input.cat_type = new Array(); //提交
		}
		
		$ionicModal.fromTemplateUrl("templates/modal/brandsOrderBy.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_brandOrderBy = modal;
		});
		//打开
		$scope.openbrandOrderBy = function() {
			if($scope.input.id) return;//编辑不能重新选择品牌
			$scope.modal_brandOrderBy.show();
		}
		//隐藏
		$scope.closebrandOrderBy = function() {
			$scope.modal_brandOrderBy.hide();
		}
		//定位到指定位置
		$scope.goToLetter = function($event,letter){
			$event.stopPropagation();//阻止事件冒泡
			$scope.currentLetter = letter;
			var height = document.getElementById(letter).offsetTop;//离顶部的距离
		 	$ionicScrollDelegate.$getByHandle("allBrands").scrollTo(0,height);
		}
		
	}

	controller.$inject = ['$scope', 'Productmanager_brand_agent_edit', 'GoAddress', 'GoDialog', 'Auth', 'GoCatTypeAuth', 'GoPage','$ionicModal','$ionicScrollDelegate','$stateParams'];

	return app.registerController("productmanager_brand_agent_editctrl",controller);
});